// pages/user/bindPhone/bindPhone.js
const md5 = require('../../../utils/md5.js')
const common = require('../../../utils/util.js')
const app = getApp()
Page({

    /**
     * 页面的初始数据
     */
    data: {
        unionID: 1,
        phone: '',
        codeTips: '获取验证码',
        isGetCode: false,
        code: ''
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {

    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {

    },

    phoneInput: function(e) {
        this.setData({
            phone: e.detail.value
        })
    },

    codeInput: function(e) {
        this.setData({
            code: e.detail.value
        })
    },

    getCode: function() {
        if (!(/^1\d{10}$/.test(this.data.phone))) {
            wx.showToast({
                title: '手机号有误',
                icon: 'none',
                duration: 2000
            })
            return
        }
        if (this.data.isGetCode) {
            return
        }
        const that = this
        let data = {
            phone: this.data.phone
        }
        common.post('Sms/send_sms', data).then(function(res) {
            if (res.code == 'isv.BUSINESS_LIMIT_CONTROL') {
                wx.showModal({
                    title: '提示',
                    content: '验证码获取次数过多，请稍后再试',
                    showCancel: false,
                    success(res) {}
                })
                return
            }
            wx.showToast({
                title: '验证码已发送',
                icon: 'success',
                duration: 1000
            })
            let time = 60
            that.setData({
                isGetCode: true
            })
            that.setData({
                codeTips: time + '秒后重新获取'
            })
            let timeClock = setInterval(function() {
                if (time > 1) {
                    time--
                    that.setData({
                        codeTips: time + '秒后重新获取'
                    })
                } else {
                    that.setData({
                        codeTips: '获取验证码'
                    })
                    that.setData({
                        isGetCode: false
                    })
                    clearInterval(timeClock)
                }
            }, 1000)
        }).catch(function(e) {})
    },

    sureBind: function() {
        if (this.data.code == '') {
            wx.showToast({
                title: '请填写验证码',
                icon: 'none',
                duration: 2000
            })
            return
        }
        wx.showLoading({
            title: '登录中...',
        })
        const that = this
        let data
        if (wx.getStorageSync('userShare')) {
            data = {
                belong_refer: wx.getStorageSync('userShare'),
                phone: that.data.phone,
                code: that.data.code,
                activity: 785
            }
        } else {
            data = {
                phone: that.data.phone,
                code: that.data.code,
                activity: 785
            }
        }
        common.post('Login/wx_phone_bing', data).then(function(res) {
            wx.hideLoading();
            if (res.code == 204) {
                wx.showModal({
                    title: '提示',
                    content: res.error,
                    showCancel: false,
                    success(res) {}
                })
            } else {
                wx.hideLoading()
                wx.setStorageSync('loginStatus', false)
                wx.setStorageSync('token', res.token)
                wx.setStorageSync("roleType", res.role_type)
                wx.setStorageSync("storeId", res.store_id)
                wx.setStorageSync("userId", res.user_id)
                wx.setStorageSync("userPhone", res.phone)
                //注册formId
                common.post('User/up_form_id', {
                    form_id: wx.getStorageSync('loginFormid')
                }).then(function(res) {}).catch(function(e) {})
                //浏览记录
                common.post('Userbrowse/add_user_browse', {
                    type: 1
                }).then(function(res) {}).catch(function(e) {})
                if (res.is_unoid == 0) {
                    that.setData({
                        unionID: 0
                    })
                    wx.setStorageSync('unionID', 0)
                } else {
                    wx.setStorageSync('unionID', 1)
                    if (wx.getStorageSync('prePageUrl').split('?')[0] == '/pages/index/index' || wx.getStorageSync('prePageUrl') == '/pages/cart/cart' || wx.getStorageSync('prePageUrl') == '/pages/user/userCenter/userCenter') {
                        wx.switchTab({
                            url: wx.getStorageSync('prePageUrl')
                        })
                    } else {
                        wx.redirectTo({
                            url: wx.getStorageSync('prePageUrl')
                        })
                    }
                }
            }
        }).catch(function(e) {})
    },

    getUserInfo: function(e) {
        const that = this
        if (e.detail.errMsg == 'getUserInfo:ok') {
            wx.showLoading({
                title: '加载中',
            })
            let data = {
                code: wx.getStorageSync('code'),
                phone: wx.getStorageSync('userPhone'),
                wx_sm: 1,
                encryptedData: e.detail.encryptedData,
                iv: e.detail.iv
            }
            common.post('Login/phone_unionid', data).then(function(res) {
                wx.login({
                    success(loginRes) {
                        wx.setStorageSync('code', loginRes.code)
                    }
                })
                if (res.code == 204) {
                    wx.hideLoading()
                    wx.setStorageSync('unionID', 0)
                    wx.showModal({
                        title: '提示',
                        content: '网络繁忙，请重新授权',
                        showCancel: false,
                        success(res) {}
                    })
                } else {
                    wx.hideLoading()
                    wx.setStorageSync('unionID', 1)
                    if (wx.getStorageSync('prePageUrl').split('?')[0] == '/pages/index/index' || wx.getStorageSync('prePageUrl') == '/pages/cart/cart' || wx.getStorageSync('prePageUrl') == '/pages/user/userCenter/userCenter') {
                        wx.switchTab({
                            url: wx.getStorageSync('prePageUrl')
                        })
                    } else {
                        wx.redirectTo({
                            url: wx.getStorageSync('prePageUrl')
                        })
                    }
                }
            }).catch(function(e) {})
        } else {
            wx.setStorageSync('unionID', 0)
            if (wx.getStorageSync('prePageUrl').split('?')[0] == '/pages/index/index' || wx.getStorageSync('prePageUrl') == '/pages/cart/cart' || wx.getStorageSync('prePageUrl') == '/pages/user/userCenter/userCenter') {
                wx.switchTab({
                    url: wx.getStorageSync('prePageUrl')
                })
            } else {
                wx.redirectTo({
                    url: wx.getStorageSync('prePageUrl')
                })
            }
        }
    },

    objKeySort: function(obj) {
        let newkey = Object.keys(obj).sort()
        let newObj = {}
        for (let i = 0; i < newkey.length; i++) {
            newObj[newkey[i]] = obj[newkey[i]]
        }
        return newObj
    }
})